//二次封装axios网络请求，配置拦截器
import axios from "axios";
import { ElMessage,ElLoading } from "element-plus";
import { GET_TOKEN } from "./token";
import { saveAs } from 'file-saver'

let downloadLoadingInstance;

console.log('当前环境：',import.meta.env.VITE_APP_TITLE)
//创建axios实例
let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
});
//请求拦截器
request.interceptors.request.use((config) => {
  //携带header头发送请求
  config.headers.token = GET_TOKEN();
  return config;
});
//响应拦截器
request.interceptors.response.use(
  (response) => {
    let msg = "";
    let isSuccess = 0;
    switch (response.data.code) {
      case 200:
        isSuccess = 1;
        break;
      case 201:
        isSuccess = 0;
        msg = "操作失败";
        break;
      case 203:
        isSuccess = 0;
        msg = "服务异常";
        break;
      default:
        if(response.status == 200){
          isSuccess = 1;
        }else{
          isSuccess = 0;
          msg = "未知错误码";
        }
    }
    if (isSuccess == 0) {
      ElMessage({
        type: "error",
        message: msg,
      });
    }
    return Promise.resolve(response.data);
  },
  (error) => {
    //处理网络错误
    let msg = "";
    if (error.response) {
      let status = error.response.status;
      switch (status) {
        case 401:
          msg = "token过期";
          break;
        case 403:
          msg = "无权访问";
          break;
        case 404:
          msg = "请求地址错误";
          break;
        case 500:
          msg = "服务器出现问题";
          break;
        default:
          msg = "无网络";
      }
      ElMessage({
        type: "error",
        message: msg,
      });
    } else {
      console.log(error);
      ElMessage({
        type: "error",
        message: "请求超时",
      });
    }

    return Promise.reject(error);
  },
);

// 通用下载方法
export function download(url, filepath,filename, config) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return request.post(url, {filepath}, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    downloadLoadingInstance.close();
    const blob = new Blob([data])
    saveAs(blob, filename)
    return Promise.resolve(data)
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
    return Promise.reject(r)
  })
}

export default request;
